﻿using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Com.Core.Helps;
using Web.Models;
using Web.Models.ViewModels;
using Dos.Common;

namespace Web.Areas.ManagerArea.Controllers
{
    public class AccountController : Controller
    {
        // GET: ManagerArea/Account
        public ActionResult Login()
        {
            //初始化Session，否则客户端不会生成ASP.NET_SessionId的Cookie，也将导致session直接丢失。
            HttpContext.Session.Add("test", "");
            return View();
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model)
        {
            var result = new DbResult();
            if (ModelState.IsValid)
            {
                var cc = new CaptchaControl();
                if (cc.CaptchaIsExpires())
                {
                    result.Message = "图形验证码失效，请刷新图形验证码";
                    return new LowerCamelJsonResult(result);
                }
                if (!cc.CaptchaValidate(model.VerCode))
                {
                    result.Message = "图形验证码错误";
                    return new LowerCamelJsonResult(result);
                }
                if (model.UserName.Equals("superadmin") && model.Password.Equals("woshichaojiguanliyuan,nizhidaoma"))
                {
                    Session["SuperAdmin"] = true;
                    Session["AdminUserName"] = "superadmin";
                    Session["AdminRealName"] = "我是超管";
                    result.StatusCode = 0;
                    result.Message = "success";
                    return new LowerCamelJsonResult(result);
                }
                using (var db = MyDbContext.Create())
                {
                    var admin = db.Admins.SingleOrDefault(m => m.UserName.Equals(model.UserName) && !m.IsDeleted);
                    if (null == admin)
                    {
                        result.Message = "账号或密码错误";
                    }
                    else
                    {
                        string password = PasswordHelper.EncryptPassword(model.Password, admin.SecurityStamp);
                        if (password.Equals(admin.Password))
                        {
                            Session["AdminId"] = admin.Id;
                            Session["AdminUserName"] = admin.UserName;
                            Session["AdminRealName"] = admin.RealName;
                            result.StatusCode = 0;
                            result.Message = "success";
                        }
                        else
                        {
                            result.Message = "账号或密码错误";
                        }
                    }
                    return new LowerCamelJsonResult(result);
                }
            }
            result.Message = "";
            foreach (var key in ModelState.Keys)
            {
                foreach (var error in ModelState[key].Errors)
                {
                    result.Message += $"{error.ErrorMessage}<br>";
                }
            }
            return new LowerCamelJsonResult(result);
        }

        public ActionResult Captcha()
        {
            #region 一些测试设置

            var captchaControl = new CaptchaControl
            {
                IsBackgroundDynamic = true,
                IsForegroundDynamic = true,
                Height = 38,
                Width = 145,
                Fonts = new List<CaptchaFontArrayItem>()
                {
                    new CaptchaFontArrayItem(new Font("Broadway", 1)),
                    new CaptchaFontArrayItem(new Font("Cooper Black", 1))
                },
                BackColor = Color.Bisque,
                ContentField = CharacterContentField.DigitOnly,
                ColorMode = Dos.Common.ColorMode.RandomColor,
                ForeColor = Color.CadetBlue,
                ToolTip = "点击验证码可更换",
                NoiseMode = NoisyRate.MiddleNoisy
            };

            #endregion
            var h = new Captcha();
            var imageStream = new MemoryStream();
            string str = h.GenerateCaptchaImage(imageStream);
            h.ProcessRequest();
            return View();
        }
    }
}